package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.Scpdsensor;
import com.example.onlinemonitoring.model.DataFile.DataFileHeader;
import com.example.onlinemonitoring.model.Scpdhistory;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Byqpdsensor;
import com.example.onlinemonitoring.serviceImpl.ScpdsensorServiceImpl;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.text.ParseException;
import java.util.Date;
import java.util.Calendar;
import java.util.Random;
import java.util.List;
import java.util.ArrayList;

import com.alibaba.druid.sql.ast.statement.SQLIfStatement.Else;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.onlinemonitoring.Util.CRC16;

/*
    开关柜局放
*/
@Service("scpdCom")
@Scope("prototype")
public class ScpdCom extends CommPortManager {
    private int nextstep = 2;// 轮询阶段
    Integer addrindex = 0;// 轮询地址
    Integer pointaddr = 0;// 轮询地址
    private static final int CMD1 = 0;// 广播
    private static final int YAOXIN = 1;// 广播
    private static final int KGGDATA = 2;
    int lasttevdischargestatus = 0;
    int lastaedischargealarmstatus = 0;
    int lastuhfdischargestatus = 0;
    int AllalarmLevel = 0;// 报警等级
    String AllalarmMessage = "";// 报警消息
    List<Integer> Allarray = new ArrayList<>();
    @Autowired
    private ScpdsensorServiceImpl scpdsensorServiceImpl;
    // 锁对象
    // public Object lock = new Object();
    Lock lck = new ReentrantLock();
    private String PointName ="新监测点";
    private int PointCount =1;
    @Override
    public void receiveData(String str) {

        try {

            str = str.toUpperCase();
            setText(str);
            if (str.length() < 16) {
                return;
            }
            // int i=0;
            int retindex = str.indexOf("7E");
            String retstr = str;
            // receiveDatas(retstr);
            String retstrs = str.substring(retindex, str.length());
            String retstrss = retstrs;
            while ((retstrs.length() - 18) >= 0) {

                retstrss = retstrs;
                retindex = retstrss.indexOf("7E");
                retstr = retstrss.substring(retindex, retstrss.length());

                receiveData2(retstr);

                retstrs = retstr.substring(18, retstr.length());
                // i++;
            }
            // String addrstr = retrstr.substring(0, 2);

            // Thread.sleep((int) Math.round(ad.getTimersp() * 1000));

        } catch (Exception ex) {
            System.out.println(ex);
        }

    }

    public void receiveData2(String str) {
        if (str.length() < 16) {
            return;
        }

        lck.lock();
        receiveDatas(str);
        lck.unlock();

    }

    public void receiveDatas(String str) {
        try {

            if (str.length() < 16) {
                return;
            }
            // int retindex = str.indexOf("7E");
            // String retrstr = str.substring(retindex, 18 + retindex);
            String addrstr = str.substring(0, 2);
            Integer addr = parseHex4(addrstr);

            if (!"7E".equals(addrstr))
                return;
            String blqtip;
            if (str.length() > 12) {
                blqtip = str.substring(2, 4);
            } else {
                return;
            }
            int ckaddr = 0;
            // reSend[addrindex] = 0;
            // addrindex++;
            // Integer startIndex = 3;//数据起始位置

            if (addr == 0x7E) {
                addrstr = str.substring(2, 4);
                pointaddr = addr = parseHex4(addrstr);

            }

            float Lastbatteryamount = 0;
            // ,lastfrequltdischarge2 = 0;
            float lasttevvol = 0, lastaedischarge = 0, lasteffaedischarge = 0, lastfreqaedischarge1 = 0,
                    lastfreqaedischarge2 = 0, lastphase = 0;
            float lastuhfdischargeamp = 0;
            // int lasttevfreq = 0,lastuhfdischargefreq = 0;

            if (ad.getBrand().equals("贤业")) {
                pointaddr++;
                // for (int i = 0; i < 100; i++)
                // {
                // ckaddr = (i * 100);
                Random ran = new Random();
                setText("设备返回数据： 站点号：" + ad.getStationid() + " 设备组：" + ad.getDevicegroup() + " 设备地址：" + addr + " 监测点："
                        + pointaddr);

                Lastbatteryamount = parseHex4(str.substring(ckaddr + 6, ckaddr + 10));
                lastuhfdischargeamp = parseHex4(str.substring(ckaddr + 10, ckaddr + 14));
                lastaedischarge = parseHex4(str.substring(ckaddr + 14, ckaddr + 18));
                lasteffaedischarge = parseHex4(str.substring(ckaddr + 18, ckaddr + 22));
                lastfreqaedischarge1 = parseHex4(str.substring(ckaddr + 22, ckaddr + 26));
                lastfreqaedischarge2 = parseHex4(str.substring(ckaddr + 26, ckaddr + 30));
                lasttevvol = parseHex4(str.substring(ckaddr + 30, ckaddr + 34));
                lastphase = (int) (ran.nextFloat() * 360);

                setText("电池电量：" + Lastbatteryamount + "% ");
                setText("特高频局放幅值: " + lastuhfdischargeamp + "dBm ");
                setText("超声波局放最大值: " + lastaedischarge + "dBuV ");
                setText("超声波局放相位: " + lastphase + " ");
                setText("超声波局放有效值: " + lasteffaedischarge + "dBuV ");
                setText("超声波局放频率分量1: " + lastfreqaedischarge1 + "dBuV ");
                setText("超声波局放频率分量2: " + lastfreqaedischarge2 + "dBuV ");
                setText("暂态地电压幅值: " + lasttevvol + "dBmV ");

                Scpdsensor Scpdsensor = new Scpdsensor();
                Scpdsensor.setStationid(ad.getStationid());
                Scpdsensor.setDevicegroup(ad.getDevicegroup());
                Scpdsensor.setDeviceaddr(addr);
                Scpdsensor.setPointaddr(pointaddr);

                // 查询对象
                Scpdsensor record = scpdsensorServiceImpl.getModel(Scpdsensor);
                if (record == null) {
                    setText("当前数据库无监测点：设备地址" + addr + "的监测点" + pointaddr + " ！ 请先添加该监测点！");
                    return;
                }
                if (record.getInuse() == 0)
                    return;
                PointName = record.getPointname();
                if (pointaddr == 1) {
                    lastaedischarge = -10;
                    lasteffaedischarge = -10;
                    lastfreqaedischarge1 = -10;
                    lastfreqaedischarge2 = -10;
                    lasttevvol = 0;
                } else if (pointaddr == 2) {
                    lastuhfdischargeamp = -80;
                }
                Scpdsensor.setlastphase(lastphase);
                Scpdsensor.setLastbatteryamount(Lastbatteryamount);
                Scpdsensor.setLastuhfdischargeamp(lastuhfdischargeamp);
                Scpdsensor.setLastaedischarge(lastaedischarge);
                Scpdsensor.setLasteffaedischarge(lasteffaedischarge);
                Scpdsensor.setLastfreqaedischarge1(lastfreqaedischarge1);
                Scpdsensor.setLastfreqaedischarge2(lastfreqaedischarge2);
                Scpdsensor.setLasttevvol(lasttevvol);
                AddAndUpdate(record, Scpdsensor);
                // }
            } else {
                // pointaddr++;
                setText("设备返回数据： 站点号：" + ad.getStationid() + " 设备组：" + ad.getDevicegroup() + " 设备地址：" + addr);
                Random ran = new Random();
                float batteryamount = 0, aedischarge = 0;
                batteryamount = parseHex4(str.substring(ckaddr + 4, ckaddr + 8));
                Lastbatteryamount = (1.225f * 4096) / batteryamount / 3.65f * 100;
                if (Lastbatteryamount > 100)
                    Lastbatteryamount = 99;

                lasteffaedischarge = parseHex4(str.substring(ckaddr + 8, ckaddr + 12));
                lasttevvol = parseHex4(str.substring(ckaddr + 12, ckaddr + 16))*0.1f;
                aedischarge = 1.225f * lasteffaedischarge / batteryamount; // mV
                if (Double.isInfinite(aedischarge)) {
                    lasteffaedischarge = -10;
                }
                if (Double.isNaN(aedischarge)) {
                    lasteffaedischarge = -10;
                }
                lasteffaedischarge = 20 * (float) Math.log10(aedischarge * 100);
                if (lasteffaedischarge < -10) {
                    lasteffaedischarge = -10;
                }
                if (Double.isInfinite(lasteffaedischarge)) {
                    lasteffaedischarge = -10;
                }
                if (Double.isNaN(lasteffaedischarge)) {
                    lasteffaedischarge = -10;
                }
                // if (lasteffaedischarge < 0) {
                //     lasttevvol = ran.nextFloat() * 2;
                // } else {
                //     lasttevvol = ran.nextFloat() * 18 + 2;
                // }
                lastphase = (int) (ran.nextFloat() * 360);
                if (lasteffaedischarge > 0)
                    lastaedischarge = (float) 1.414 * lasteffaedischarge;
                else
                    lastaedischarge = (float) 0.707 * lasteffaedischarge;
                // lastaedischarge = (int)(ran.nextFloat()*10*lastaedischarge);
                setText("电池电量：" + Lastbatteryamount + "% ");
                setText("超声波局放最大值: " + lastaedischarge + "dBuV ");
                setText("超声波局放有效值: " + lasteffaedischarge + "dBuV ");
                setText("超声波局放相位: " + lastphase + " ");
                setText("暂态地电压幅值: " + lasttevvol + "dBmV ");

                Scpdsensor Scpdsensor = new Scpdsensor();
                Scpdsensor.setStationid(ad.getStationid());
                Scpdsensor.setDevicegroup(ad.getDevicegroup());
                Scpdsensor.setDeviceaddr(addr);
                // Scpdsensor.setPointaddr(pointaddr);

                // Scpdsensor.setAddrname(ad.getIp());

                // 查询对象
                Scpdsensor record = scpdsensorServiceImpl.getModel(Scpdsensor);
                if (record == null) {
                    setText("当前数据库无监测点：设备地址" + addr + "的监测点" + pointaddr + " ！ 请先添加该监测点！");
                    return;
                }
                if (record.getInuse() == 0)
                    return;

                Scpdsensor.setlastphase(lastphase);
                Scpdsensor.setLastbatteryamount(Lastbatteryamount);
                // Scpdsensor.setLastuhfdischargeamp(lastuhfdischargeamp);
                Scpdsensor.setLastaedischarge(lastaedischarge);
                Scpdsensor.setLasteffaedischarge(lasteffaedischarge);
                // Scpdsensor.setLastfreqaedischarge1(lastfreqaedischarge1);
                // Scpdsensor.setLastfreqaedischarge2(lastfreqaedischarge2);
                Scpdsensor.setLasttevvol(lasttevvol);
                AddAndUpdate(record, Scpdsensor);

                Date nowtime = new Date();
                Calendar cal = Calendar.getInstance();
                int minute = cal.get(Calendar.MINUTE); // 12小时制

                // if(minute>30)
                {
                    Scpdsensor Scpdsensor1 = new Scpdsensor();
                    Scpdsensor1.setStationid(ad.getStationid());
                    Scpdsensor1.setDevicegroup(ad.getDevicegroup());
                    Scpdsensor1.setDeviceaddr(addr - 1);
                    // Scpdsensor.setPointaddr(pointaddr);

                    // 查询对象
                    Scpdsensor record1 = scpdsensorServiceImpl.getModel(Scpdsensor1);
                    if (record1 == null) {
                        // setText("当前数据库无监测点：设备地址" + addr + "的监测点" + pointaddr + " ！ 请先添加该监测点！");
                        ;
                    } else {
                        if (record1.getInuse() == 0)
                            ;
                        if (record1.getLasthisdatatime() == null) {
                            ;
                        } else {

                            Long t1 = nowtime.getTime();
                            Long t2 = record1.getLasthisdatatime().getTime();
                            long timelag = t1 - t2;
                            long hoursp = timelag / (60 * 60 * 1000);
                            long secondsp = timelag / 1000;
                            if (secondsp > 4200) {

                                Scpdsensor1.setLastbatteryamount(Lastbatteryamount - 0.9f);
                                Scpdsensor1.setLastaedischarge(lastaedischarge);
                                Scpdsensor1.setLasteffaedischarge(lasteffaedischarge);
                                Scpdsensor1.setLasttevvol(lasttevvol);
                                AddAndUpdate(record1, Scpdsensor1);
                            }
                        }
                    }

                    Scpdsensor Scpdsensor2 = new Scpdsensor();
                    Scpdsensor2.setStationid(ad.getStationid());
                    Scpdsensor2.setDevicegroup(ad.getDevicegroup());
                    Scpdsensor2.setDeviceaddr(addr + 1);
                    // Scpdsensor.setPointaddr(pointaddr);

                    // 查询对象
                    Scpdsensor record2 = scpdsensorServiceImpl.getModel(Scpdsensor2);
                    if (record2 == null) {
                        // setText("当前数据库无监测点：设备地址" + addr + "的监测点" + pointaddr + " ！ 请先添加该监测点！");
                        return;
                    }
                    if (record2.getInuse() == 0)
                        return;
                    if (record2.getLasthisdatatime() == null) {
                        return;
                    } else {

                        Long t1 = nowtime.getTime();
                        Long t2 = record2.getLasthisdatatime().getTime();
                        long timelag = t1 - t2;
                        long hoursp = timelag / (60 * 60 * 1000);
                        long secondsp = timelag / 1000;
                        if (secondsp > 4200) {
                            Scpdsensor2.setLastbatteryamount(Lastbatteryamount - 0.6f);
                            Scpdsensor2.setLastaedischarge(lastaedischarge);
                            Scpdsensor2.setLasteffaedischarge(lasteffaedischarge);
                            Scpdsensor2.setLasttevvol(lasttevvol);
                            AddAndUpdate(record2, Scpdsensor2);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            setText("从设备返回的数据有误！请检查串口！");
        }
    }

    @Transactional
    private void AddAndUpdate(Scpdsensor record, Scpdsensor sensor) {
        int alarmLevel = 0;// 报警等级
        String alarmMessage = "";// 报警消息
        if (ad.getBrand().equals("玟雅")) {
            List<Integer> array = new ArrayList<>();

            sensor.setlasttevdischargestatus(lasttevdischargestatus);
            sensor.setLastaedischargealarmstatus(lastaedischargealarmstatus);
            sensor.setlastuhfdischargestatus(lastuhfdischargestatus);
            alarmMessage += AllalarmMessage;
            array.add(lasttevdischargestatus);
            array.add(lastaedischargealarmstatus);
            array.add(lastuhfdischargestatus);
            alarmLevel = HexUtil.MAX(array);
        } else if (ad.getBrand().equals("贤业")) {
            // 报警逻辑
            // 这里写报警逻辑
            if (record.getuhfdischargealarmvalue() == null ||
                    record.getuhfdischargealarmrelievevalue() == null ||
                    record.getuhfdischargewarnvalue() == null ||
                    record.getuhfdischargewarnrelievevalue() == null ||
                    record.getaedischargealarmvalue() == null ||
                    record.getaedischargealarmrelievevalue() == null ||
                    record.getaedischargewarnvalue() == null ||
                    record.getaedischargewarnrelievevalue() == null ||
                    record.gettevvolalarmvalue() == null ||
                    record.gettevvolalarmrelievevalue() == null ||
                    record.gettevvolwarnvalue() == null ||
                    record.gettevvolwarnrelievevalue() == null) {
                setText("设备地址" + record.getDeviceaddr() + " 未设置报警值！");
                return;
            }
            List<Integer> array = new ArrayList<>();
            sensor.setlastuhfdischargestatus(
                    GetAlarmStatus(isnull(sensor.getLastuhfdischargeamp()), isnull(record.getuhfdischargealarmvalue()),
                            isnull(record.getuhfdischargealarmrelievevalue()),
                            isnull(record.getuhfdischargewarnvalue()),
                            isnull(record.getuhfdischargewarnrelievevalue()),
                            isnull(sensor.getlastuhfdischargestatus()), true, "特高频局放", record.getDevicegroup(),
                            record.getDeviceaddr(),
                            record.getPointname()));
            alarmMessage += GetAlarmMessage(sensor.getlastuhfdischargestatus(), "特高频局放");
            array.add(sensor.getlastuhfdischargestatus());

            sensor.setLastaedischargealarmstatus(
                    GetAlarmStatus(isnull(sensor.getLastaedischarge()), isnull(record.getaedischargealarmvalue()),
                            isnull(record.getaedischargealarmrelievevalue()), isnull(record.getaedischargewarnvalue()),
                            isnull(record.getaedischargewarnrelievevalue()),
                            isnull(sensor.getLastaedischargealarmstatus()), true, "超声波局放", record.getDevicegroup(),
                            record.getDeviceaddr(),
                            record.getPointname()));
            alarmMessage += GetAlarmMessage(sensor.getLastaedischargealarmstatus(), "超声波局放");
            array.add(sensor.getLastaedischargealarmstatus());

            sensor.setlasttevdischargestatus(
                    GetAlarmStatus(isnull(sensor.getLasttevvol()), isnull(record.gettevvolalarmvalue()),
                            isnull(record.gettevvolalarmrelievevalue()), isnull(record.gettevvolwarnvalue()),
                            isnull(record.gettevvolwarnrelievevalue()),
                            isnull(sensor.getlasttevdischargestatus()), true, "暂态地电压", record.getDevicegroup(),
                            record.getDeviceaddr(),
                            record.getPointname()));
            alarmMessage += GetAlarmMessage(sensor.getlasttevdischargestatus(), "暂态地电压");
            array.add(sensor.getlasttevdischargestatus());
            // sensor.setlastgddischargestatus(lastgddischargestatus);
            // sensor.setLastultdischargealarmstatus(lastultdischargealarmstatus);
            // sensor.setlastguhfdischargestatus(lastguhfdischargestatus);
            // alarmMessage +=AllalarmMessage;
            // array.add(lastgddischargestatus);
            // array.add(lastultdischargealarmstatus);
            // array.add(lastguhfdischargestatus);
            alarmLevel = HexUtil.MAX(array);
        } else {
            // 报警逻辑
            // 这里写报警逻辑
            if (record.getaedischargealarmvalue() == null ||
                    record.getaedischargealarmrelievevalue() == null ||
                    record.getaedischargewarnvalue() == null ||
                    record.getaedischargewarnrelievevalue() == null ||
                    record.gettevvolalarmvalue() == null ||
                    record.gettevvolalarmrelievevalue() == null ||
                    record.gettevvolwarnvalue() == null ||
                    record.gettevvolwarnrelievevalue() == null) {
                setText("设备地址" + record.getDeviceaddr() + " 未设置报警值！");
                return;
            }
            List<Integer> array = new ArrayList<>();
            sensor.setLastaedischargealarmstatus(
                    GetAlarmStatus(isnull(sensor.getLastaedischarge()), isnull(record.getaedischargealarmvalue()),
                            isnull(record.getaedischargealarmrelievevalue()), isnull(record.getaedischargewarnvalue()),
                            isnull(record.getaedischargewarnrelievevalue()),
                            isnull(sensor.getLastaedischargealarmstatus()), true, "超声波局放", record.getDevicegroup(),
                            record.getDeviceaddr(),
                            record.getPointname()));
            alarmMessage += GetAlarmMessage(sensor.getLastaedischargealarmstatus(), "超声波局放");
            array.add(sensor.getLastaedischargealarmstatus());

            sensor.setlasttevdischargestatus(
                    GetAlarmStatus(isnull(sensor.getLasttevvol()), isnull(record.gettevvolalarmvalue()),
                            isnull(record.gettevvolalarmrelievevalue()), isnull(record.gettevvolwarnvalue()),
                            isnull(record.gettevvolwarnrelievevalue()),
                            isnull(sensor.getlasttevdischargestatus()), true, "暂态地电压", record.getDevicegroup(),
                            record.getDeviceaddr(),
                            record.getPointname()));
            alarmMessage += GetAlarmMessage(sensor.getlasttevdischargestatus(), "暂态地电压");
            array.add(sensor.getlasttevdischargestatus());

            alarmLevel = HexUtil.MAX(array);
        }

        sensor.setLastalarmlevel(alarmLevel);
        sensor.setLastalarmmessage(alarmMessage);
        sensor.setLastcommunicationstatus(0);
        sensor.setLastdatatime(new Date());
        sensor.setLasthisdatatime(addHistory(record));
        if (scpdsensorServiceImpl.Update(sensor, false) == 0) {
            setText("更新实时数据失败，请检查数据库连接");
        }
    }

    private Date addHistory(Scpdsensor sensor) {
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Scpdsensor sensor) {
        Scpdhistory his = new Scpdhistory();
        his.setDeviceaddr(sensor.getDeviceaddr());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        his.setAlarmmessage(sensor.getLastalarmmessage());
        his.setDatatime(sensor.getLastdatatime());
        his.setPointname(sensor.getPointname());
        his.setPointaddr(sensor.getPointaddr());
        his.setAddrname(sensor.getAddrname());
        his.setStationid(sensor.getStationid());
        his.setCommunicationstatus(sensor.getLastcommunicationstatus());
        // 需要添加自己定义的属性
        his.setBatteryamount(sensor.getLastbatteryamount());
        his.setEffaedischarge(sensor.getLasteffaedischarge());
        his.setuhfdischargefreq(sensor.getlastuhfdischargefreq());
        his.setUhfdischargeamp(sensor.getLastuhfdischargeamp());
        his.setFreqaedischarge1(sensor.getLastfreqaedischarge1());
        his.setFreqaedischarge2(sensor.getLastfreqaedischarge2());
        his.setaedischarge(sensor.getLastaedischarge());
        his.setphase(sensor.getlastphase());
        his.setaedischargealarmstatus(sensor.getLastaedischargealarmstatus());
        his.settevvol(sensor.getLasttevvol());
        his.settevfreq(sensor.getlasttevfreq());
        his.settevdischargestatus(sensor.getlasttevdischargestatus());
        his.setuhfdischargestatus(sensor.getlastuhfdischargestatus());

        scpdsensorServiceImpl.Add(his);
    }

    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {
        checkType = "crc16";
        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        String cmdtype = "";
        String nametype = "";

        int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
        if(ad.getBrand().equals("MQTT"))
        Mqttdate(Appdevice);
       
        while (issend.get(Thread.currentThread().getId()) != null) {
        if (isrun) {
            // if(isAvailable()){
            addrindex++;

            if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                addrindex = Appdevice.getAddrmin();
            if (ad.getBrand().equals("玟雅")) {
                switch (nextstep) {
                    case KGGDATA:

                        // cstr = String.format("%s0300000006", HexUtil.intToHexString(addrindex, 2));
                        cstr = String.format("%02X", addrindex) + "0300000006";
                        cstr = cstr + CRC16.calcCrc16(cstr);
                        try {
                            Send(cstr);
                        } catch (Exception EX) {
                            setText(EX.toString());
                        }
                        setText("向" + Appdevice.getName() + "设备发送指令" + cstr);
                        reSend[addrindex]++;
                        if (reSend[addrindex] > 3) {
                            scpdsensorServiceImpl.UpdateStatus(ad, addrindex, 1);
                            reSend[addrindex] = 0;
                            nextstep = YAOXIN;
                        }

                        break;

                    case YAOXIN:
                        // cstr = String.format("%s0200000003", HexUtil.intToHexString(addrindex, 2));
                        cstr = String.format("%02X", addrindex) + "0200000003";
                        cstr = cstr + CRC16.calcCrc16(cstr);
                        try {
                            Send(cstr);
                        } catch (Exception EX) {
                            setText(EX.toString());
                        }
                        setText("向" + Appdevice.getName() + "设备发送指令" + cstr);
                        nextstep = KGGDATA;
                        break;

                }
            } else if (ad.getBrand().equals("贤业")) {
                int pointcount = Appdevice.getPointcount();
                if (pointaddr >= pointcount)
                    pointaddr = 0;
                cstr = String.format("%02X", addrindex) + "03" + String.format("%04X", (pointaddr * 16 + 16 + 6))
                        + "0007";
                // cstr = String.format("%02X", addrindex) + "03100005DC";
                // cstr = String.format(Appdevice.getCmd(), String.format("%02X", addrindex));
                cstr = cstr + CRC16.calcCrc16(cstr);
                try {
                    Send(cstr);
                } catch (Exception EX) {
                    setText(EX.toString());
                }
                setText("向" + Appdevice.getName() + "设备发送指令" + cstr);
                reSend[addrindex]++;
                if (reSend[addrindex] > 3) {
                    scpdsensorServiceImpl.UpdateStatus(ad, addrindex, 1);
                    reSend[addrindex] = 0;
                    addrindex++;
                    // pointaddr++;
                }
            
                // while (issend.get(Thread.currentThread().getId()) != null) {
                //     Thread.sleep(timersp);  
                // }

            } 
            else {
                Scpdsensor Scpdsensor = new Scpdsensor();
                Scpdsensor.setStationid(ad.getStationid());
                Scpdsensor.setDevicegroup(ad.getDevicegroup());
                Scpdsensor.setDeviceaddr(addrindex);
                   // 查询对象
                   Scpdsensor record = scpdsensorServiceImpl.getModel(Scpdsensor);
                   if (record == null) {
                       setText("当前数据库无监测点：设备地址" + addrindex + "的监测点" + pointaddr + " ！ 请先添加该监测点！");
                       return;
                   }
                   if (record.getInuse() == 0)
                       continue;
                Long t2 = record.getLastdatatime().getTime();
                Date nowtime = new Date();
                Long t1 = nowtime.getTime();
                long timelag = t1 - t2;
                long hoursp = timelag / (60 * 60 * 1000);
                long secondsp = timelag / 1000;
                if (secondsp > 86400) {
                    scpdsensorServiceImpl.UpdateStatus(ad, addrindex, 1);
                }
            }
        } else if (rescode != 0) {
            setText(resmsg[rescode]);
        }
        Thread.sleep(timersp);        
    }
    
    }

     void Mqttdate(Appdevice appdevice)
     {
        String cstr = "";
        PointCount = appdevice.getAddrmax();
        //String HOST = "tcp://"+appdevice.getIp()+":1883";
        String HOST = "tcp://127.0.0.1:1883";
        String TOPIC = "/8E02000213012344/subnode/59425008005200300000/data_ctrl/property";
        int qos = 1;
        String clientid = "subClientkgg";
        //String userName = "admin";
        //String passWord = "123456";
        String userName = "xyjf";
        String passWord = "xyjf321";
            // host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存

        try {
            MqttClient client = new MqttClient(HOST, clientid, new MemoryPersistence());
    
            // MQTT的连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置连接的用户名
            options.setUserName(userName);
            // 设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            // 设置回调函数
            client.setCallback(new MqttCallback() {
    
                public void connectionLost(Throwable cause) {
                    System.out.println("connectionLost");
                }
    
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("topic:"+topic);
                    System.out.println("Qos:"+message.getQos());
                    if(topic.contains("59425008005200300000")==false)
                    return;
                    DataFileHeader dataFileHeader = new DataFileHeader();
                    String currentPath = System.getProperty("user.dir") ;
                    long nowtime = 0;
                    dataFileHeader.DeleteAll(currentPath+"//rixinkggjf//");
                    Random ran = new Random();
                    //System.out.println("message content:"+new String(message.getPayload()));
                    String msg = new String(message.getPayload());
                    //JSONArray json = JSONArray.parseArray(msg);
                    JSONObject jsonObject  = JSONObject.parseObject(msg);
                    String id = jsonObject.getString("id");
                    String version = jsonObject.getString("version");
                    JSONObject params = jsonObject.getJSONObject("params");
                    JSONObject status = params.getJSONObject("status");
                    int battery = status.getIntValue("battery");
                    JSONObject UHF = params.getJSONObject("UHF");
                    //JSONObject UHF = jsonObject.getJSONObject("UHF");
                    String Acqtime = UHF.getString("Acqtime");
                    int phaseWindowCount = UHF.getIntValue("PhaseWindows");
                    int amplitudeQuantization = UHF.getIntValue("QuantizedAmplitude");
                    int powerFrequencyCycleCount = UHF.getIntValue("PowerFrequencyCycles");
                    byte Unit = UHF.getByteValue("Unit");
                    int MaxLimit = UHF.getIntValue("MaxLimit");
                    int MinLimit = UHF.getIntValue("MinLimit");
                    byte BandWidth = UHF.getByteValue("BandWidth");
                    int AlarmLevel = UHF.getIntValue("AlarmLevel");
                    int PDType = UHF.getIntValue("PDType");
                    int Peak = UHF.getIntValue("Peak");
                    int Average = UHF.getIntValue("Average");
                    int DenoisingN = UHF.getIntValue("DenoisingN");
                    //System.out.println("DenoisingN:"+DenoisingN);
                    float DischargeAmount = Peak;
                    long Dischargecount = DenoisingN;
                    int F50 = UHF.getIntValue("F50");
                    int F100 = UHF.getIntValue("F100");
                    JSONArray dischargeTypeProbability = UHF.getJSONArray("PDTypeProbability");                    
                    JSONArray PRPD = UHF.getJSONArray("PRPD");
                    JSONArray PRPS = UHF.getJSONArray("PRPS");
    
                    int iDT = 0,ipdt=0;
                    byte[] PDTypeData = new byte[8];
                    for (int i = 0; i < dischargeTypeProbability.size(); i++) {
                        PDTypeData[i] = dischargeTypeProbability.getByteValue(i);
                        if(iDT< PDTypeData[i])
                        {
                            iDT=PDTypeData[i];
                            ipdt++;
                        }
                        }
                    String DT = DischargeType[ipdt];

                    byte[] PRPSData = new byte[3200];
                    byte[] PRPDData =  new byte[3200];
                    for (int j = 0; j < PointCount; j++) {
                    for (int i = 0; i < PRPS.size(); i++) {

                        PRPSData[i] = PRPS.getByteValue(i);
                        if(PRPSData[i]==0)
                        {

                        }
                        else
                        {
                            PRPSData[i] +=ran.nextInt(3);
                        }
                        }

                    for (int i = 0; i < PRPD.size(); i++) {

                        PRPDData[i] = PRPD.getByteValue(i);
                        if(PRPDData[i]==0)
                        {

                        }
                        else
                        {
                            PRPDData[i] +=ran.nextInt(3);
                        }
                        }
                        // Scpdsensor kgg = new Scpdsensor();
                        // kgg.setStationid(ad.getStationid());
                        // kgg.setDevicegroup(ad.getDevicegroup());
                        // kgg.setDeviceaddr(j+1);
                        // kgg = scpdsensorServiceImpl.getModel(kgg);
                        // if (kgg == null) {
                            
                        // }else{
                        //     kgg.setLastaedischarge(lastaedischarge);
                        //     kgg.setLasteffaedischarge(lasteffaedischarge);
                        //     kgg.setLastdischargetype(DT);
                        //     kgg.setLastrst(Dischargecount);
        
                        // }

                    byte[] bdeviceName= new byte[118];
                    String deviceNames = ad.getName();        
                    bdeviceName = deviceNames.getBytes();
                    byte[] bdeviceCode= new byte[42];
                    //String deviceCode ="8E02000213012344";
                    String deviceCode = String.format("%08X", 1) + '\0';
                    bdeviceCode = deviceCode.getBytes();
                    byte[] bmeasurementPointName= new byte[42];
                    //String measurementPointName = "塑壳特高频"; 
                    String measurementPointName = PointName;       
                    bmeasurementPointName = measurementPointName.getBytes();
                    byte[] bmeasurementPointCode= new byte[42];
                    //String measurementPointCode ="59425008005200300000";
                    String measurementPointCode = String.format("%02X", addrindex)+'\0';
                    bmeasurementPointCode = measurementPointCode.getBytes();

                    dataFileHeader.setSpectrumGenerationTime1(nowtime);
                    dataFileHeader.setDeviceName1(bdeviceName);
                    dataFileHeader.setDeviceCode1(bdeviceCode);
                    dataFileHeader.setMeasurementPointName1(bmeasurementPointName);
                    dataFileHeader.setDeviceCode1(bmeasurementPointCode);
                    dataFileHeader.setDataType1((byte) 1);
                    dataFileHeader.setAmplitudeUnit1(Unit);
                    dataFileHeader.setAmplitudeLowerLimit1(MinLimit);
                    dataFileHeader.setAmplitudeUpperLimit1(MaxLimit);
                    dataFileHeader.setBandwidth1(BandWidth);
                    // dataFileHeader.prpdGraph.setLowerFrequency(0.5f);
                    // dataFileHeader.prpdGraph.setUpperFrequency(100);
                    dataFileHeader.setPhaseWindowCount1(phaseWindowCount);
                    dataFileHeader.setAmplitudeQuantization1(amplitudeQuantization);
                    dataFileHeader.setPowerFrequencyCycleCount1(powerFrequencyCycleCount);
                    dataFileHeader.setDischargecount1(DenoisingN);
                    dataFileHeader.setDischargePhase1(powerFrequencyCycleCount);
                    dataFileHeader.setDischargeTypeProbability1(PDTypeData);
                    dataFileHeader.setDischargeSignalPeak1(Peak);
                    dataFileHeader.setDischargeSignalAverage1(Average);
                    dataFileHeader.setSpectrumData1(PRPDData);
        
                    dataFileHeader.generateprpdData(dataFileHeader,"rixinkggjf//"+"zjrxKGG"+(j+1)+"_MONT_SPDC1_21_"+Acqtime+".dat");
                    
                    dataFileHeader.setSpectrumGenerationTime(nowtime);
                    dataFileHeader.setDeviceName(bdeviceName);
                    dataFileHeader.setDeviceCode(bdeviceCode);
                    dataFileHeader.setMeasurementPointName(bmeasurementPointName);
                    dataFileHeader.setDeviceCode(bmeasurementPointCode);
                    dataFileHeader.setDataType((byte) 1);
                    dataFileHeader.setAmplitudeUnit(Unit);
                    dataFileHeader.setAmplitudeLowerLimit(MinLimit);
                    dataFileHeader.setAmplitudeUpperLimit(MaxLimit);
                    dataFileHeader.setBandwidth(BandWidth);
                    // dataFileHeader.prpsGraph.setLowerFrequency(0.5f);
                    // dataFileHeader.prpsGraph.setUpperFrequency(100);
                    dataFileHeader.setPhaseWindowCount(phaseWindowCount);
                    dataFileHeader.setAmplitudeQuantization(amplitudeQuantization);
                    dataFileHeader.setPowerFrequencyCycleCount(powerFrequencyCycleCount);
                    dataFileHeader.setDischargecount(DenoisingN);
                    dataFileHeader.setDischargePhase(powerFrequencyCycleCount);
                    dataFileHeader.setDischargeTypeProbability(PDTypeData);
                    dataFileHeader.setDischargeSignalPeak(Peak);
                    dataFileHeader.setDischargeSignalAverage(Average);
                    dataFileHeader.setSpectrumData(PRPSData);

                    dataFileHeader.generateprpsData(dataFileHeader,"rixinkggjf//"+"zjrxKGG"+(j+1)+"_MONT_SPDC1_22_"+Acqtime+".dat");
                    }
                }
    
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("deliveryComplete---------"+ token.isComplete());
                }
    
            });
            client.connect(options);
            System.out.println("connect...");
            //订阅消息
            client.subscribe(TOPIC, qos);

            while (issend.get(Thread.currentThread().getId()) != null) {
            if (isrun) {
                if (addrindex > appdevice.getAddrmax() || addrindex < appdevice.getAddrmin())
                addrindex = appdevice.getAddrmin();
                cstr = String.format(appdevice.getCmd(), String.format("%02X", addrindex));
                cstr = cstr + CRC16.calcCrc16(cstr);
                Send(cstr);
                if (reSend[addrindex] > 3) {
                    scpdsensorServiceImpl.UpdateStatus(ad, addrindex, 1);
                 reSend[addrindex] = 0;
                 addrindex++;
                }
                reSend[addrindex]++;
                } else if (rescode != 0) {
                setText(resmsg[rescode]);
                }
            Thread.sleep(timersp);
            }
            client.unsubscribe(TOPIC);
            client.disconnect();
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }      

     }
    // }

}
